package cn.cmkj.auction.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jude.rollviewpager.RollPagerView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.ShuhuaImagePagerAdapter;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Auction;
import cn.cmkj.auction.data.http.AuctionOrder;
import cn.cmkj.auction.data.http.ShuhuaImage;
import cn.cmkj.auction.data.http.ShuhuaProps;
import cn.cmkj.auction.data.model.AliPayResult;
import cn.cmkj.auction.utils.DisplayUtil;
import cn.cmkj.auction.utils.DoubleUtil;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.Utils;
import cn.cmkj.auction.widget.AlertDialog;
import cn.cmkj.auction.widget.PriceUpDialog;

/**
 * Created by cunguoyao on 2018/2/9.
 */
@ContentView(R.layout.activity_auction_detail)
public class AuctionDetailActivity extends BaseActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener {

    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.swipeRefreshLayout)
    private SwipeRefreshLayout swipeRefreshLayout;
    @ViewInject(R.id.roll_view_pager)
    private RollPagerView rollPagerView;
    private int height;
    @ViewInject(R.id.pai_layout_ok)
    private RelativeLayout layoutPaiOk;//竞拍成功
    @ViewInject(R.id.pai_price_user)
    private TextView paiPriceUser;//中拍者
    @ViewInject(R.id.pai_price_chengjiao)
    private TextView paiPriceMoney;//中拍价格
    @ViewInject(R.id.pai_layout_not_ok)
    private RelativeLayout layoutPaiNotOk;//竞拍进行中or结束
    @ViewInject(R.id.pai_price)
    private TextView paiPrice;//当前价
    @ViewInject(R.id.pai_price_time_text)
    private TextView paiPriceTimeText;//距离时间文字
    @ViewInject(R.id.pai_price_time)
    private TextView paiPriceTime;//距离时间

    @ViewInject(R.id.price_start_up)
    private TextView priceStartUp;//起步价
    @ViewInject(R.id.price_mark_up)
    private TextView priceMarkUp;//加价幅度
    @ViewInject(R.id.price_bond)
    private TextView priceBond;//保证金

    @ViewInject(R.id.shu_props)
    private LinearLayout propsLayout;
    @ViewInject(R.id.shu_brief)
    private WebView shuBriefText;

    @ViewInject(R.id.layout_price_live)
    private RelativeLayout priceLiveLayout;
    @ViewInject(R.id.ib_call)
    private ImageButton ibCall;
    @ViewInject(R.id.ib_fav)
    private ImageButton ibFav;
    @ViewInject(R.id.btn_buy)
    private Button buyButton;

    private Auction auction;
    private Callback.Cancelable post;
    private Timer timer;
    private long timeCoumpter;
    private List<ShuhuaImage> shuhuaImages;
    private ShuhuaImagePagerAdapter imagePagerAdapter;

    private AuctionOrder order;
    private PriceUpDialog priceDialog;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    AliPayResult payResult = new AliPayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(AuctionDetailActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(AuctionDetailActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        auction = (Auction) getIntent().getSerializableExtra("auction");
        if(auction == null) {
            finish();
            return;
        }
        timer = new Timer();
        shuhuaImages = new ArrayList<>();
        List<ShuhuaImage> images = new ArrayList<>();
        images.addAll(auction.getImages());
        shuhuaImages.addAll(images);
        imagePagerAdapter = new ShuhuaImagePagerAdapter(this, shuhuaImages);
        rollPagerView.setAdapter(imagePagerAdapter);
        ViewGroup.LayoutParams layoutParams = rollPagerView.getLayoutParams();
        layoutParams.height = Utils.getScreenWidth(this) * 9 / 16;
        layoutParams.width = Utils.getScreenWidth(this);
        rollPagerView.setLayoutParams(layoutParams);

        int fontSize = (int) getResources().getDimension(R.dimen.dp_12);
        WebSettings webSettings = shuBriefText.getSettings();
        webSettings.setDefaultFontSize(fontSize);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        titleText.setText(auction.getName());
        titleBack.setOnClickListener(this);
        priceLiveLayout.setOnClickListener(this);
        ibCall.setOnClickListener(this);
        ibFav.setOnClickListener(this);
        buyButton.setOnClickListener(this);
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setEnabled(true);
        //进入页面自动刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                fetchAuctionInfo();
                fetchGoodsContextInfo();
            }
        });
    }

    @Override
    public void onRefresh() {
        fetchAuctionInfo();
        fetchGoodsContextInfo();
    }

    private void fetchAuctionInfo() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.auctionGoodsDetail);
        params.addParameter("auction_id", auction.getId());
        User user = getAccount();
        if(user != null) {
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
        }
        post = x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                swipeRefreshLayout.setRefreshing(false);
                JSONObject jsonStr = null;
                try {
                    jsonStr = new JSONObject(s);
                    JSONObject json = jsonStr.optJSONObject("data");
                    auction = Auction.parseFromJsonForDetail(json);
                    fillData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void cancel(CancelledException e) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void fetchGoodsContextInfo() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.goodsIntro);
        params.addParameter("goods_id", auction.getGoodsId());
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                swipeRefreshLayout.setRefreshing(false);
                JSONObject jsonStr = null;
                try {
                    jsonStr = new JSONObject(s);
                    JSONObject json = jsonStr.optJSONObject("data");
                    String webData = json.optString("goods_context");
                    shuBriefText.loadData(webData, "text/html; charset=UTF-8", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void cancel(CancelledException e) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void fillData() {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Drawable drawable= getResources().getDrawable(R.drawable.shu_desc_point);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        if(auction.getProps() != null && auction.getProps().size() > 0) {
            propsLayout.removeAllViews();
            for(ShuhuaProps prop : auction.getProps()) {
                TextView mTextView = new TextView(this);
                mTextView.setCompoundDrawables(drawable,null,null,null);//设置TextView的drawableleft
                mTextView.setCompoundDrawablePadding(DisplayUtil.dip2px(this, 10));//设置图片和text之间的间距
                mTextView.setPadding(DisplayUtil.dip2px(this, 15), DisplayUtil.dip2px(this, 10), 0, DisplayUtil.dip2px(this, 0));
                mTextView.setTextSize(16);
                mTextView.setTextColor(getResources().getColor(R.color.b_80));
                mTextView.setText(prop.name + "：" + prop.value);
                propsLayout.addView(mTextView, layoutParams);
            }
        }
        switch (auction.getStatus()) {
            case 0://未开始
                if(auction.isFrontMoney()) {
                    priceLiveLayout.setVisibility(View.VISIBLE);
                }else {
                    priceLiveLayout.setVisibility(View.GONE);
                }
                layoutPaiOk.setVisibility(View.GONE);
                layoutPaiNotOk.setVisibility(View.VISIBLE);
                paiPrice.setText("￥" + auction.getNowPrice().doubleValue());
                if(auction.isFrontMoney()) {
                    buyButton.setEnabled(false);
                    buyButton.setText("等待开始");
                }else {
                    buyButton.setEnabled(true);
                    buyButton.setText("缴纳保证金");
                }
                paiPriceTimeText.setText("距开始:");
                long startTime = auction.getFromTime();
                long nowTime = System.currentTimeMillis() / 1000;
                timeCoumpter = startTime - nowTime;
                if(timer != null) {
                    timer.cancel();
                    timer = null;
                }
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                timeCoumpter --;
                                long hh = timeCoumpter / 60 / 60 % 60;
                                long mm = timeCoumpter / 60 % 60;
                                long ss = timeCoumpter % 60;
                                paiPriceTime.setText(hh + "小时" + mm + "分钟" + ss + "秒");
                            }
                        });
                    }
                }, 0, 1000);
                break;
            case 1://已经开始
                if(auction.isFrontMoney()) {
                    priceLiveLayout.setVisibility(View.VISIBLE);
                }else {
                    priceLiveLayout.setVisibility(View.GONE);
                }
                layoutPaiOk.setVisibility(View.GONE);
                layoutPaiNotOk.setVisibility(View.VISIBLE);
                paiPrice.setText("￥" + auction.getNowPrice().doubleValue());
                if(auction.isFrontMoney()) {
                    buyButton.setEnabled(true);
                    buyButton.setText("出价");
                }else {
                    buyButton.setEnabled(true);
                    buyButton.setText("缴纳保证金");
                }
                paiPriceTimeText.setText("距结束:");
                long endTimes = auction.getToTime();
                long nowTimes = System.currentTimeMillis() / 1000;
                timeCoumpter = endTimes - nowTimes;
                if(timer != null) {
                    timer.cancel();
                    timer = null;
                }
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                timeCoumpter --;
                                long hh = timeCoumpter / 60 / 60 % 60;
                                long mm = timeCoumpter / 60 % 60;
                                long ss = timeCoumpter % 60;
                                paiPriceTime.setText(hh + "小时" + mm + "分钟" + ss + "秒");
                            }
                        });
                    }
                }, 0, 1000);
                break;
            case 2://已结束
                priceLiveLayout.setVisibility(View.VISIBLE);
                if(TextUtils.isEmpty(auction.getDealAccount())) {
                    layoutPaiOk.setVisibility(View.GONE);
                    layoutPaiNotOk.setVisibility(View.VISIBLE);
                    paiPrice.setText("￥" + auction.getNowPrice().doubleValue());
                    paiPriceTimeText.setVisibility(View.GONE);
                    paiPriceTime.setVisibility(View.GONE);
                }else {
                    layoutPaiOk.setVisibility(View.VISIBLE);
                    layoutPaiNotOk.setVisibility(View.GONE);
                    paiPriceUser.setText(auction.getDealAccount());
                    paiPriceMoney.setText("￥" + auction.getDealPrice().doubleValue());
                }
                buyButton.setEnabled(false);
                buyButton.setText("已结束");
                break;
        }
        priceStartUp.setText("￥" + auction.getStartPrice().doubleValue());
        priceMarkUp.setText("￥" + auction.getPriceMarkup().doubleValue());
        priceBond.setText("￥" + auction.getBond().doubleValue());
    }

    private void call() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Urls.TEL_KF));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void addFav() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.addFav);
        params.addParameter("goods_id", auction.getGoodsId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            auction.setFav(true);
                            ibFav.setImageResource(R.drawable.icon_fav_ed);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(AuctionDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(AuctionDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void delFav() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.delFav);
        params.addParameter("goods_id", auction.getGoodsId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            auction.setFav(false);
                            ibFav.setImageResource(R.drawable.icon_fav);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(AuctionDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(AuctionDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void popGivePriceDialog() {
        if(priceDialog == null) {
            priceDialog = new PriceUpDialog(this).builder().setTitle("提示")
                    .setMsg("当前竞拍价格为￥" + auction.getNowPrice() + ",加价幅度不小于￥" + auction.getPriceMarkup() + ",请输入竞拍价")
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String money = priceDialog.getEditText().getText().toString();
                            if(TextUtils.isEmpty(money)) {
                                Toast.makeText(AuctionDetailActivity.this, "请输入价格", Toast.LENGTH_SHORT).show();
                            }else {
                                double price = Double.valueOf(money);
                                price = DoubleUtil.sub(price, auction.getNowPrice().doubleValue());
                                double beishu = new BigDecimal((100*price) % (100*auction.getPriceMarkup().doubleValue())).doubleValue();
                                if(beishu != 0) {
                                    Toast.makeText(AuctionDetailActivity.this, "请输入加价幅度的整数倍价格", Toast.LENGTH_SHORT).show();
                                }else {
                                    givePrice(money);
                                }
                            }
                        }
                    }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            priceDialog.dismiss();
                        }
                    }).setPlus(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String priceStr = priceDialog.getEditText().getText().toString();
                            double price = 0;
                            //if(Utils.isValidMoney(priceStr)) {
                                price = Double.valueOf(priceStr);
                            //}
                            price = DoubleUtil.sum(price, auction.getPriceMarkup().doubleValue());
                            priceDialog.setEditText(String.valueOf(price));
                        }
                    }).setReduce(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String priceStr = priceDialog.getEditText().getText().toString();
                            double price = 0;
                            //if(Utils.isValidMoney(priceStr)) {
                                price = Double.valueOf(priceStr);
                            //}
                            price = DoubleUtil.sub(price, auction.getPriceMarkup().doubleValue());
                            if(price < auction.getNowPrice().doubleValue())price = auction.getNowPrice().doubleValue();
                            priceDialog.setEditText(String.valueOf(price));
                        }
                    }).setEditText(String.valueOf(auction.getNowPrice().doubleValue()))
                    .setCancelable(true).setCanceledOnTouchOutside(false);
            priceDialog.show();
        }else {
            priceDialog.show();
        }
    }

    private void givePrice(String money) {//出价
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.auctionUpSale);
        params.addParameter("auction_id", auction.getId());
        params.addParameter("money", money);
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(AuctionDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }else {
                            AlertDialog msgDialog = new AlertDialog(AuctionDetailActivity.this);
                            msgDialog.builder().setTitle("提示").setMsg("恭喜您出价成功！请在拍卖结束后至拍卖订单中完成支付。")
                                    .setCancelable(true).setPositiveButton("确定", new View.OnClickListener(){
                                        @Override
                                        public void onClick(View view) {
                                            if(priceDialog != null) {
                                                priceDialog.dismiss();
                                            }
                                        }
                                    }).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(AuctionDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.layout_price_live:
                Intent intent = new Intent(this, AuctionPriceListActivity.class);
                intent.putExtra("auction", auction);
                startActivity(intent);
                break;
            case R.id.ib_call:
                call();
                break;
            case R.id.ib_fav:
                if(auction.isFav()) {
                    delFav();
                }else {
                    addFav();
                }
                break;
            case R.id.btn_buy:
                if(auction.isFrontMoney()) {//缴纳过保证金
                    if(auction.getStatus() == 1 || auction.getStatus() == 2) {//出价
                        popGivePriceDialog();
                    }
                }else {//没缴纳过保证金
                    if(auction.getStatus() == 1 || auction.getStatus() == 2) {//保证金
                        Intent intent1 = new Intent(this, OrderAuctionDetailActivity.class);
                        intent1.putExtra("auctionId", ""+auction.getId());
                        startActivityForResult(intent1, 1);
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(true);
                        fetchAuctionInfo();
                        fetchGoodsContextInfo();
                    }
                });
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(post != null && !post.isCancelled()) {
            post.cancel();
        }
    }
}
